//
//  NetworkTools.swift
//  weibo
//
//  Created by tomato on 2021/9/21.
//

import UIKit
import Alamofire
import Alamofire

/// Swift 中枚举不仅支持Int 类型, 还支持字符串和其它基本类型等
enum AlamofireRequestMethod: String {
    case GET = "GET"
    case POST = "POST"
}

class NetworkAlamofireTools{
    //单例
    static let sharedInstance: NetworkAlamofireTools = {
        let tools = NetworkAlamofireTools()
        return tools
    }()
}
    
//MARK: 定义网络请求的公共方法
extension NetworkAlamofireTools{
    func request(urlString: String, method: AlamofireRequestMethod, parameters: Any?, success: @escaping (Any?)->(), failure: @escaping (Any?)->()) {
        // 配置公共信息
        Alamofire.SessionManager.default.adapter = NetConfig()
        Alamofire.request(urlString, method: getRequestMethod(method: method), parameters: parameters as? Parameters, encoding: URLEncoding.default, headers: nil).responseJSON { (response) in
            
            switch response.result {
            case .success(let json):
                Print(items:"成功回调:json: \(json)")
                success(json)
            case .failure(let error):
                Print(items:"失败回调:error: \(error.localizedDescription)")
                failure(error)
            }
        }.validate { (request, response, data) -> Request.ValidationResult in
//            Print(items:"validate中的response: \(response)")
            guard let _ = data else {
                return .failure(NSError(domain: "没有数据", code: 9999, userInfo: nil))
            }
            if response.statusCode == 404 {
                return .failure(NSError(domain: "系统繁忙", code: response.statusCode, userInfo: nil))
            }
            return .success
        }
    }
    
    // MARK: 网络请求方式
    private func getRequestMethod(method: AlamofireRequestMethod) -> (HTTPMethod) {
        if method == .GET {
            return HTTPMethod.get
        } else {
            return HTTPMethod.post
        }
    }
}

//MARK: 各个模块网络
extension NetworkAlamofireTools{
    
    //网络测试服务器:http://httpbin.org/get
    func NetworkTest(){
        request(urlString: "http://httpbin.org/get", method:.GET, parameters: ["name":"刘德华","age":"18"]) { (result) in
        } failure: { (err) in
        }
    }
    
    //获取授权信息(access_token) -> 去开放平台OAuth2.0 授权中看需要的参数和结果
    func loadAccessToken(code:String,success: @escaping (Any?)->(), failure: @escaping (Any?)->()){
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let parameters = [
            "client_id": client_id,
            "client_secret": client_secret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirect_url
        ]
        request(urlString: urlString, method: .POST, parameters: parameters) { (result) in
            success(result)
        } failure: { (err) in
            failure(err)
        }
    }
    
    //请求用户信息
    func getUserInfo(accessToken:String,userID:String,success: @escaping (Any?)->(), failure: @escaping (Any?)->()){
        
        let urlString = "https://api.weibo.com/2/users/show.json"
        let parameters = [
            "access_token": accessToken,
            "uid": userID,
        ]
        
        request(urlString: urlString, method: .GET, parameters: parameters) {  (result) in
            success(result)
        } failure: { (err) in
            failure(err)
        }
    }
    
    //请求首页数据
    func getHomeListRequest(accessToken:String,success: @escaping (Any?)->(), failure: @escaping (Any?)->()){
        
        let urlString = "https://api.weibo.com/2/users/show.json"
        let parameters = [
            "access_token": accessToken
        ]
        request(urlString: urlString, method: .GET, parameters: parameters) {  (result) in
            success(result)
        } failure: { (err) in
            failure(err)
        }
    }
    
    
    ///加载本地json数据
    /// - Parameters:
    ///   - fileName: 文件名字
    ///   - success: success
    ///   - failure: failure
    func getHomeListWithLocalJson(fileName:String,success: @escaping (Any?)->(), failure: @escaping (Any?)->()){
        
        // 获取本地 JSON 文件的路径
        guard let path = Bundle.main.path(forResource: fileName, ofType: "json") else {
            Print(items:"无法找到 JSON 文件")
            return
        }
        // 读取 JSON 文件内容
        do {
            let data = try Data(contentsOf: URL(fileURLWithPath: path))
            // 解析 JSON 数据
            let jsonObject = try JSONSerialization.jsonObject(with: data, options: [])
            // 将 JSON 数据转换为字典
            guard let dictionary = jsonObject as? [String: Any] else {
               return
            }
            guard let dataArray = dictionary ["statuses"] as? [[String: Any]] else {
                return
            }
            //将json转换为model数组
            guard let statusAarray = [Status].deserialize(from:dataArray) else {
                return
            }
            success(statusAarray)
        } catch {
            Print(items: "加载 JSON 文件失败：\(error)")
        }
    }
}
